'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class HomeController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = 'hi, egg';
    }
    //登录
    async login(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && password){
            let target = await service.home.login(username,password);

            if(target.length){
                let token = jwt.sign({...target[0]},'lixd',{expiresIn:60*60*5});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    role_id:target[0].role_id,
                    role_name:target[0].role_name,
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //获取菜单
    async menuList(){
        let {ctx,service} = this;
        let {role_id} = ctx.query;
        //容错处理
        if(role_id){
            let list = await service.home.menuList(role_id);
            ctx.body = {
                code:1,
                data:list
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = HomeController;
